package com.mcxx.modules.temporary.order.service.read;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.mcxx.common.exception.BizException;
import com.mcxx.constant.DictConstant;
import com.mcxx.modules.BaseParam;
import com.mcxx.modules.base.service.read.AreaHelper;
import com.mcxx.modules.base.service.read.DictionaryReadService;
import com.mcxx.modules.base.utils.QueryParamUtil;
import com.mcxx.modules.miniSalvation.check.dto.CheckFamilyDTO;
import com.mcxx.modules.miniSalvation.check.dto.IntegrateCheckDTO;
import com.mcxx.modules.miniSalvation.check.dto.ProResultDTO;
import com.mcxx.modules.miniSalvation.family.entity.BankEntity;
import com.mcxx.modules.miniSalvation.family.service.read.BankReadService;
import com.mcxx.modules.miniSalvation.order.dao.read.OrderInHouseReadDao;
import com.mcxx.modules.miniSalvation.order.dto.NoticeDTO;
import com.mcxx.modules.miniSalvation.order.dto.OrderInHouseDTO;
import com.mcxx.modules.miniSalvation.order.entity.OrderEntity;
import com.mcxx.modules.miniSalvation.order.param.OrderBizStateParam;
import com.mcxx.modules.system.dto.AuditConfirmListDTO;
import com.mcxx.modules.system.dto.PdfApproveDTO;
import com.mcxx.modules.system.dto.PdfApproveDetailDTO;
import com.mcxx.modules.temporary.cancel.entity.TmpCancelEntity;
import com.mcxx.modules.temporary.family.dto.SalvationResultDTO;
import com.mcxx.modules.temporary.family.dto.TempMemberExcelDto;
import com.mcxx.modules.temporary.family.dto.TmpFamilyExcelDTO;
import com.mcxx.modules.temporary.family.param.SalvationFamilyParam;
import com.mcxx.modules.temporary.family.param.SalvationObjectParam;
import com.mcxx.modules.temporary.family.service.read.TmpFamilyMemberReadService;
import com.mcxx.modules.temporary.order.dao.read.TmpOrderReadDao;
import com.mcxx.modules.temporary.order.dto.*;
import com.mcxx.modules.temporary.order.entity.TmpOrderDetailEntity;
import com.mcxx.modules.temporary.order.entity.TmpOrderEntity;
import com.mcxx.modules.temporary.order.param.OrderListSearchParam;
import com.mcxx.modules.temporary.order.param.TemporaryOrderParam;
import com.mcxx.util.CommonUtil;
import com.mcxx.util.Constant;
import com.mcxx.util.NumberConvert;
import com.yinhai.ta404.core.restservice.requestbean.PageParam;
import com.yinhai.ta404.core.restservice.resultbean.Page;
import com.yinhai.ta404.core.security.vo.UserAccountVo;
import com.yinhai.ta404.core.service.BaseService;
import com.yinhai.ta404.core.transaction.annotation.TaTransactional;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
@TaTransactional(readOnly = true)
public class TmpOrderReadService extends BaseService {

    @Autowired
    private TmpOrderReadDao tmpOrderReadDao;
    @Autowired
    private TmpFamilyMemberReadService tmpFamilyMemberReadService;
    @Autowired
    private AreaHelper areaHelper;
    @Autowired
    private OrderInHouseReadDao inHouseReadDao;
    @Autowired
    private DictionaryReadService dictionaryReadService;
    @Autowired
    private BankReadService bankReadService;


    public List<TmpOrderEntity> listAll() {
    	return tmpOrderReadDao.listAll();
    }



    public TmpOrderEntity getById(String id) {
    	return tmpOrderReadDao.getById(id);
    }


    public int getByIdCount(String id) {
        return tmpOrderReadDao.getByIdCount(id);
    }


    public OrderEntity selectInfoByIdCard(String idcard) {
        return tmpOrderReadDao.selectInfoByIdCard(idcard);
    }



    public List<TmpOrderEntity> getByOrderIds(List<String> orderIdList){
        return tmpOrderReadDao.getByOrderIds(orderIdList);
    }

    public TmpOrderDTO getOrderSarlayInfo(String orderId) {
    	return tmpOrderReadDao.getOrderSarlayInfo(orderId);
    }


    public Page getTownSalvationTodoList(TemporaryOrderParam param, PageParam pageParam, UserAccountVo accountVo) {

        QueryParamUtil.setBaseParamValue(param,accountVo);


        tmpOrderReadDao.beginPager(pageParam);
        List<TmpOrderDTO> list = tmpOrderReadDao.getTownSalvationTodoList(param);


        return tmpOrderReadDao.endPager(list);
    }


    public Page getTempApplyTodoList(TemporaryOrderParam param, PageParam pageParam, UserAccountVo accountVo) {

        QueryParamUtil.setBaseParamValue(param,accountVo);


        tmpOrderReadDao.beginPager(pageParam);
        List<TmpOrderDTO> list = tmpOrderReadDao.getTempApplyTodoList(param);


        return tmpOrderReadDao.endPager(list);
    }


    public Page getTempApplyTodoListByCountry(TemporaryOrderParam param, PageParam pageParam) {

        tmpOrderReadDao.beginPager(pageParam);
        List<TmpOrderDTO> list = tmpOrderReadDao.getTempApplyTodoList(param);


        return tmpOrderReadDao.endPager(list);
    }


    public Page getNoFinishOrderCounty(TemporaryOrderParam param, PageParam pageParam, UserAccountVo accountVo) {

        QueryParamUtil.setBaseParamValue(param,accountVo);




        tmpOrderReadDao.beginPager(pageParam);
        List<TmpOrderDTO> list = tmpOrderReadDao.queryNoFinishOrderCounty(param);


        return tmpOrderReadDao.endPager(list);
    }


    public Page listFinishedOrderTown(OrderListSearchParam param, PageParam pageParam, UserAccountVo accountVo) {

        QueryParamUtil.setBaseParamValue(param,accountVo);


        tmpOrderReadDao.beginPager(pageParam);
        List<TmpOrderDTO> list = tmpOrderReadDao.listFinishedOrderTown(param);


        return tmpOrderReadDao.endPager(list);
    }


    public Page listFinishedOrderCounty(OrderListSearchParam param, PageParam pageParam, UserAccountVo accountVo) {

        QueryParamUtil.setBaseParamValue(param,accountVo);


        tmpOrderReadDao.beginPager(pageParam);
        List<TmpOrderDTO> list = tmpOrderReadDao.listFinishedOrderCounty(param);


        return tmpOrderReadDao.endPager(list);
    }


    public List<TmpOrderDTO> getCanSendCheckOrder(List<String> orderIdList, String preBizState, String notEqBizState){
        return tmpOrderReadDao.getCanSendCheckOrder(orderIdList, preBizState, notEqBizState);
    }


    public TmpOrderDTO getStateAndVersion(String orderId){
        return tmpOrderReadDao.getStateAndVersion(orderId);
    }


    public List<TmpOrderDTO> getStateAndVersions(List<String> orderIdList){
        return tmpOrderReadDao.getStateAndVersions(orderIdList);
    }


    public String getBizStateByBizStateRange(String orderId, String preBizState){
        return tmpOrderReadDao.getBizStateByBizStateRange(orderId, preBizState);
    }




    public ApplicationDTO getDetailById(String orderId) {
        ApplicationDTO applyDto = tmpOrderReadDao.getDetailById(orderId);

        if (applyDto == null) {
            return new ApplicationDTO();
        }

        AreaHelper.AreaPo areaPo = areaHelper.getAreaByCode(applyDto.getAreaCode());
        Date applyDate = applyDto.getApplyDate();
        String applyYearStr = DateUtil.format(applyDate, "yyyy");
        int times = countByFamilyIdAndReason(applyDto.getFamilyId(), applyDto.getMainReason(), applyYearStr);


        applyDto.setAreaName(areaPo.getAreaName());
        applyDto.setTimes(times);


        setBankInfo(applyDto);
        return applyDto;
    }


    private void setBankInfo(ApplicationDTO applyDto) {
        List<BankEntity> bankList = bankReadService.getBankByApplyIdCardAndBizType(applyDto.getApplyIdcard(), Constant.BusinessCode.LINSHI);
        if (!bankList.isEmpty()) {
            BankEntity bankEntity = bankList.get(0);
            applyDto.setApplyAccount(bankEntity.getMasterAccount());
            applyDto.setApplyBankCode(bankEntity.getMasterBankCode());
            applyDto.setApplySubsideProps(bankEntity.getMasterSubsideProps());
        }
    }


    public ApplicationDTO getFinishedDetailById(String orderId) {
        ApplicationDTO applyDto = tmpOrderReadDao.getFinishedDetailById(orderId);

        if (applyDto == null) {
            return new ApplicationDTO();
        }

        AreaHelper.AreaPo areaPo = areaHelper.getAreaByCode(applyDto.getAreaCode());
        Date applyDate = applyDto.getApplyDate();
        String applyYearStr = DateUtil.format(applyDate, "yyyy");
        int times = countByFamilyIdAndReason(applyDto.getFamilyId(), applyDto.getMainReason(), applyYearStr);


        applyDto.setAreaName(areaPo.getAreaName());
        applyDto.setTimes(times);


        setBankInfo(applyDto);
        return applyDto;
    }


    public List<TmpOrderDTO> getOrderByIdAndBizStateCon(OrderBizStateParam orderBizStateParam){
        return  tmpOrderReadDao.getOrderByIdAndBizStateCon(orderBizStateParam);
    }


    public Map<String, Double> getMasterSocietyNum(String idcard, String commitDate){
        return tmpOrderReadDao.getMasterSocietyNum(idcard, commitDate);
    }


    public Page listSalvationFamily(SalvationFamilyParam param, PageParam pageParam, UserAccountVo accountVo) {

        QueryParamUtil.setBaseParamValue(param,accountVo);


        tmpOrderReadDao.beginPager(pageParam);
        List<SalvationResultDTO> list = tmpOrderReadDao.listSalvationFamily(param);


        return tmpOrderReadDao.endPager(list);
    }


    public Page listSalvationObject(SalvationObjectParam param, PageParam pageParam, UserAccountVo accountVo) {

        QueryParamUtil.setBaseParamValue(param,accountVo);


        tmpOrderReadDao.beginPager(pageParam);
        List<SalvationResultDTO> list = tmpOrderReadDao.listSalvationObject(param);


        return tmpOrderReadDao.endPager(list);
    }



    public List<TmpOrderDTO> getOrderRecordFlag(List<String> ids, String recordFlag){
        return tmpOrderReadDao.getOrderRecordFlag(ids,recordFlag);
    }



    public Map getFamilyCountSummary(SalvationFamilyParam param, UserAccountVo accountVo) {
        Map familyCountSummary;

        QueryParamUtil.setBaseParamValue(param,accountVo);

        familyCountSummary = tmpOrderReadDao.getFamilyCountSummary(param);

        return familyCountSummary;
    }


    public Map getObjectCountSummary(SalvationObjectParam param, UserAccountVo accountVo) {
        Map objectCountSummary;

        QueryParamUtil.setBaseParamValue(param,accountVo);

        objectCountSummary = tmpOrderReadDao.getObjectCountSummary(param);

        return objectCountSummary;
    }


    public int getSalvationLimit(String countyCode, String businessType, String standType) {
        return tmpOrderReadDao.getSalvationLimit(countyCode,businessType,standType);
    }


    public List<TmpOrderDTO> listTodoByFamilyId(String familyId) {
        return tmpOrderReadDao.listTodoByFamilyId(familyId);
    }


    public int countByIdCardAndMonth(String idcard, String month) {
        String familyId = tmpFamilyMemberReadService.getFamilyIdByIdCard(idcard);
        return tmpOrderReadDao.countByFamilyIdAndMonth(familyId,month);
    }


    public int countByFamilyIdAndMonth(String familyId, String month) {
        return tmpOrderReadDao.countByFamilyIdAndMonth(familyId,month);
    }


    public int countByIdCardAndReason(String idcard, String mainReason, String year) {
        String familyId = tmpFamilyMemberReadService.getFamilyIdByIdCard(idcard);
        return countByFamilyIdAndReason(familyId, mainReason, year);
    }


    public int countByFamilyIdAndReason(String familyId, String mainReason, String year) {
        DateTime dateTime = DateUtil.parse(year, "yyyy");

        String beginOfYear = DateUtil.beginOfYear(dateTime).toString("yyyyMM");

        String endOfYear = DateUtil.endOfYear(dateTime).toString("yyyyMM");
        return tmpOrderReadDao.countByFamilyIdAndReason(familyId,mainReason,beginOfYear,endOfYear);
    }


    public int countsByIdCardAndReason(String idcard, String mainReason, String year) {
        DateTime dateTime = DateUtil.parse(year, "yyyy");

        String beginOfYear = DateUtil.beginOfYear(dateTime).toString("yyyyMM");

        String endOfYear = DateUtil.endOfYear(dateTime).toString("yyyyMM");
        return tmpOrderReadDao.countsByIdcardAndReason(idcard,mainReason,beginOfYear,endOfYear);
    }


    public List<TmpOrderDTO> getOrderAndFamily(List<String> orderIdList){
        return tmpOrderReadDao.getOrderAndFamily(orderIdList);
    }


    public TmpOrderDetailEntity getAuditInfo(String orderId, String checkType) {
        return tmpOrderReadDao.getAuditInfo(orderId, checkType);
    }



    public List<TmpOrderDetailEntity> getAuditInfos(String orderId, String checkType){
        if("2".equals(checkType)){
            checkType = "'1','2'";
        }
        return tmpOrderReadDao.getAuditInfos(orderId,checkType);
    }



    public int countBacklog(BaseParam param) {
        return tmpOrderReadDao.countBacklog(param);
    }


    public List<TempMemberExcelDto> exportRescueMemberList(SalvationObjectParam param){ return tmpOrderReadDao.exportRescueMemberList(param); }


    public List<TmpFamilyExcelDTO> exportRescueFamilyList(SalvationObjectParam param){ return tmpOrderReadDao.exportRescueFamilyList(param); }


    public String getBizStateById(String id) {
        return tmpOrderReadDao.getBizStateById(id);
    }


    public String getStateById(String id) {
        return tmpOrderReadDao.getStateById(id);
    }


    public TmpOrderEntity getFamilyIdAndBizStateById(String id) {
        return tmpOrderReadDao.getFamilyIdAndBizStateById(id);
    }

    public List<CheckFamilyDTO> getCheckInfo(List<String> list){
        return tmpOrderReadDao.getCheckInfo(list);
    }

    public List<ProResultDTO> getProResult(List<String> idList){return tmpOrderReadDao.getProResult(idList);}

    public String getMasertIdcard(String orderId){return tmpOrderReadDao.getMasertIdcard(orderId);}



    public String getApplyIdcard(String orderId){return tmpOrderReadDao.getgetApplyIdcard(orderId);}


    public String queryStateByFmIdcard(String idcard, String areacode){
        return tmpOrderReadDao.queryStateByFmIdcard(idcard,areacode);
    }

    public TmpOrderStateVerifyDTO getBizStateReportFile(String orderId){
        return tmpOrderReadDao.getBizStateReportFile(orderId);
    }

    public String selectObjIdById(String orderId){
        return tmpOrderReadDao.selectObjIdById(orderId);
    }

    public List<String> cntFileObjId(List<String> orderId){
        return tmpOrderReadDao.cntFileObjId(orderId);
    }


    public OrderInHouseDTO queryLastInHouseRecord(String orderId, String userAreaLevel){
        TmpOrderEntity tmpOrderEntity = tmpOrderReadDao.getById(orderId);

        if(Constant.BizStateNew.COUNTY_IN_HOUSE_ING.equals(tmpOrderEntity.getBizState())
                || Constant.BizStateNew.IN_HOUSE_ING.equals(tmpOrderEntity.getBizState())){
            return inHouseReadDao.queryNewByOrderId(orderId, userAreaLevel);
        }
        return new OrderInHouseDTO();
    }

    public int isCanPrintNotice(String orderId){

        String bizState = tmpOrderReadDao.getBizStateById(orderId);
        if(!Constant.BizStateNew.APPROVE_REFUSE.equals(bizState) && !Constant.BizStateNew.AUDIT_REFUSE.equals(bizState)){
            throw  new BizException("-1","只有拒批的申请才能打印不予受理通知书");
        }
        return 1;
    }

    public NoticeDTO getNoticesInfo(String orderId, UserAccountVo userAccountVo){
        return tmpOrderReadDao.selectNoticeInfo(orderId);
    }

    public String getOrderObjKey(String orderId){
        return tmpOrderReadDao.getOrderObjKey(orderId);
    }


    public TmpOrderStatement selectOrderStatement(String orderId){
        TmpOrderStatement statement = tmpOrderReadDao.selectOrderStatement(orderId);


        statement.setSex(StringUtils.isBlank(statement.getSex())?"":dictionaryReadService.getCodeCache(DictConstant.SEX,statement.getSex()).getLabel());

        statement.setCensusType(StringUtils.isBlank(statement.getCensusType())?"":dictionaryReadService.getCodeCache(DictConstant.CENSUS_TYPE,statement.getCensusType()).getLabel());

        statement.setTempSaveType(StringUtils.isBlank(statement.getTempSaveType())?"":dictionaryReadService.getCodeCache(DictConstant.TemporaryType,statement.getTempSaveType()).getLabel());

        statement.setObjectType(StringUtils.isBlank(statement.getObjectType())?"":dictionaryReadService.getCodeCache(DictConstant.TEMPOBJECTTYPE,statement.getObjectType()).getLabel());

        statement.setSalvMoney("大写:"+ NumberConvert.toChinese(statement.getSalvMoney())+"(小写:￥"+statement.getSalvMoney()+")");
        String commitDate = statement.getCommitDate();
        try {
            commitDate = com.mcxx.util.DateUtil.sdf2.format(com.mcxx.util.DateUtil.sdf.parse(commitDate));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        statement.setCommitDate(commitDate);
        return  statement;
    }


    public List<TmpOrderExcelDTO> exportListTown(OrderListSearchParam param){ return tmpOrderReadDao.exportListTown(param);}


    public List<TmpOrderExcelDTO> exportListCounty(OrderListSearchParam param){ return tmpOrderReadDao.exportListCounty(param);}


    public List<TmpOrderExcelPendingDTO> exportTownSalvation(TemporaryOrderParam param){ return tmpOrderReadDao.exportTownSalvation(param);}


    public List<TmpOrderExcelPendingCDTO> exportTownSalvationCounty(TemporaryOrderParam param){ return tmpOrderReadDao.exportTownSalvationCounty(param);}


    public TmpCancelEntity selectCancelInfo(String orderId){
        return tmpOrderReadDao.selectCancelInfo(orderId);
    }


    public List<PdfApproveDTO> findPdfInfo(String operateType, String orderId, String yearMon, String areaCode){
        return tmpOrderReadDao.findPdfInfo(operateType,orderId,yearMon,areaCode);
    }


    public List<PdfApproveDetailDTO> findPdfInfoDetail(List<String> list){
        return tmpOrderReadDao.findPdfInfoDetail(list);
    }

    public List<IntegrateCheckDTO> getIntegrateCheckInfo(List<String> list){
        return tmpOrderReadDao.getIntegrateCheckInfo(list);
    }


    public OrderEntity selectInfoByApplyIdCard(String idCard) {
        return tmpOrderReadDao.selectInfoByApplyIdCard(idCard);
    }


    public List<OrderEntity> selectInfoByApplyIdCards(List<String> idcardList) {
        return tmpOrderReadDao.selectInfoByApplyIdCards(idcardList);
    }

    public AuditConfirmListDTO selectAuditConfirmListDTO(String orderId){
        return tmpOrderReadDao.selectAuditConfirmListDTO(orderId);
    }


    public List<TmpOrderDTO> listTodoByApplyIdCard(String idCard) {
        return tmpOrderReadDao.listTodoByApplyIdCard(idCard);
    }


    public Page getFamilySummaryForWxapp(SalvationFamilyParam param, PageParam pageParam) {
        if(CommonUtil.invalidArgs(param.getSaveStartMonth()) || CommonUtil.invalidArgs(param.getSaveEndMonth()) ){
            param.setSaveStartMonth(com.mcxx.util.DateUtil.getMonthString());
            param.setSaveEndMonth(com.mcxx.util.DateUtil.getMonthString());
        }
        tmpOrderReadDao.beginPager(pageParam);
        List<SalvationResultDTO> list = tmpOrderReadDao.listSalvationFamily(param);
        return tmpOrderReadDao.endPager(list);
    }


    public int getAuditNum(String areaCode) {
        return tmpOrderReadDao.getAuditNum(areaCode);
    }


    public List<TmpOrderDTO> listTodoByMemberIdCard(String idcard){
        return tmpOrderReadDao.listTodoByMemberIdCard(idcard);
    }


    public OrderEntity getApplyTodoInfo(String idCard, String areaCode) {
        return tmpOrderReadDao.getApplyTodoInfo(idCard, areaCode);
    }
}
